package edu.thu.studio.ormdesigner.editor.policy;

import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.XYLayoutEditPolicy;
import org.eclipse.gef.requests.CreateRequest;

import edu.thu.studio.ormdesigner.editor.command.CreateTableCommand;
import edu.thu.studio.ormdesigner.editor.command.CreateViewNodeCommand;
import edu.thu.studio.ormdesigner.editor.command.MoveNodeCommand;
import edu.thu.studio.ormdesigner.editor.editpart.NodeEditPart;
import edu.thu.studio.ormdesigner.editor.editpart.DiagramEditPart;
import edu.thu.studio.ormdesigner.model.diagram.Diagram;
import edu.thu.studio.ormdesigner.model.diagram.node.Node;
import edu.thu.studio.ormdesigner.model.diagram.node.TableNode;
import edu.thu.studio.ormdesigner.model.diagram.node.ViewNode;

public class DiagramLayoutEditPolicy extends XYLayoutEditPolicy {
    
    protected Command createAddCommand(EditPart child, Object constraint) {
        return null;
    }
    
    /**
     * {@inheritDoc}
     */
    @Override
    protected Command createChangeConstraintCommand(EditPart child, Object constraint) {
        Diagram diagram = (Diagram) this.getHost().getModel();
        Rectangle rectangle = (Rectangle) constraint;
        
        NodeEditPart editPart = (NodeEditPart) child;
        Node nodeElement = (Node) editPart.getModel();
        Rectangle currentRectangle = editPart.getFigure().getBounds();
        
        return new MoveNodeCommand(diagram, currentRectangle, rectangle.x, rectangle.y, rectangle.width,
            rectangle.height, nodeElement);
    }
    
    /**
     * {@inheritDoc}
     */
    @Override
    protected Command getCreateCommand(CreateRequest request) {
        DiagramEditPart editPart = (DiagramEditPart) this.getHost();
        
        Point point = request.getLocation();
        editPart.getFigure().translateToRelative(point);
        
        Node element = (Node) request.getNewObject();
        element.setRectangle(point.x, point.y, Node.DEFAULT_WIDTH, Node.DEFAULT_HEIGHT);
        
        Diagram diagram = (Diagram) editPart.getModel();
        if (element instanceof ViewNode) {
            return new CreateViewNodeCommand(diagram, (ViewNode) element);
        } else if (element instanceof TableNode) {
            return new CreateTableCommand(diagram, (TableNode) element);
        }
        return null;
    }
    
    protected Command getDeleteDependantCommand(Request request) {
        return null;
    }
    
}
